const shortid = require('shortid');
const db = require('../utils/db.js');
const { cryptMsg } = require('../utils/index');

const defaultUsers = [
  { name: 'liuzunkun', password: 'abcd1234' },
  { name: 'ds', password: 'abcd1234' },
  { name: 'admin', password: 'abcd1234' },
];

function initUsers() {
  defaultUsers.forEach(item => {
    const user = db.get('users').find({ name: item.name }).value();
    if (!user) {
      const { salt, hash } = cryptMsg(item.password);
      db.get('users')
        .push({
          id: shortid.generate(),
          name: item.name,
          password: hash,
          salt,
        })
        .write();
    }
  });
}

function start() {
  initUsers();
}

module.exports = { start };
